package cn.jjxx.modules.sys.controller;

import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.utils.CookieUtils;
import cn.jjxx.core.utils.JeewebPropertiesUtil;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.oa.entity.OaNotification;
import cn.jjxx.modules.oa.service.IOaNotificationService;
import cn.jjxx.modules.sys.Constants;
import cn.jjxx.modules.sys.entity.Menu;
import cn.jjxx.modules.sys.entity.SysHomePageManageUser;
import cn.jjxx.modules.sys.entity.SysHomepageManage;
import cn.jjxx.modules.sys.security.shiro.realm.UserRealm;
import cn.jjxx.modules.sys.security.shiro.web.filter.authc.UsernamePasswordToken;
import cn.jjxx.modules.sys.service.ISysHomePageManageUserService;
import cn.jjxx.modules.sys.service.ISysHomepageManageService;
import cn.jjxx.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("${admin.url.prefix}")
public class IndexController {
    @Autowired
    private IOaNotificationService oaNotificationService;
    @Autowired
    private ISysHomepageManageService iSysHomepageManageService;
    @Autowired
    private ISysHomePageManageUserService iSysHomePageManageUserService;

    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        // 加载菜单
        model.addAttribute("menus", UserUtils.getMenuList());
        // 加载通知公告
        int oaNotificationCount = oaNotificationService
                .selectCount(new EntityWrapper<OaNotification>(OaNotification.class).eq("status", "1"));
        List<OaNotification> oaNotifications = oaNotificationService
                .selectList(new EntityWrapper<OaNotification>(OaNotification.class).eq("status", "1"));
        model.addAttribute("oaNotificationCount", oaNotificationCount);
        model.addAttribute("oaNotifications", oaNotifications);
        // 加载模版
        String theme = getTheme(request);
        String linkUrl = "modules/sys/index/index-" + theme;
        /*boolean bo = false;
        //查询是否关联首页
        EntityWrapper<SysHomePageManageUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("user_id", UserUtils.getUser().getId());
        List<SysHomePageManageUser> list = iSysHomePageManageUserService.selectList(entityWrapper);
        if (list.size() > 0) {
            EntityWrapper<SysHomepageManage> homepageManageEntityWrapper = new EntityWrapper<>();
            homepageManageEntityWrapper.eq("id", list.get(0).getHomePageId());
            List<SysHomepageManage> sysHomepageManages = iSysHomepageManageService.selectList(homepageManageEntityWrapper);
            if (sysHomepageManages.size() > 0) {
                linkUrl = sysHomepageManages.get(0).getHomePageLink();
            } else {
                bo = true;
            }
        } else {
            bo = true;
        }
        if (bo) {
            EntityWrapper<SysHomepageManage> homepageManageEntityWrapper = new EntityWrapper<>();
            homepageManageEntityWrapper.eq("is_default", "1");
            List<SysHomepageManage> sysHomepageManages = iSysHomepageManageService.selectList(homepageManageEntityWrapper);
            if (sysHomepageManages.size() > 0) {
                linkUrl = sysHomepageManages.get(0).getHomePageLink();
            }
        }*/
        //密码验证
        String url = "admin/login?logout=1";
        UserRealm.Principal p = UserUtils.getPrincipal();
        //验证密码2020-9-1
        try {
            if (p != null) {
                Object value = UserUtils.getCache(Constants.PWD_SESSION + p.getSessionid());
                UsernamePasswordToken authcToken = null;
                if (value != null) {
                    authcToken = (UsernamePasswordToken) value;
                    String pwd = String.valueOf(authcToken.getPassword());
                    if (com.baomidou.mybatisplus.toolkit.StringUtils.isNotEmpty(pwd)) {
                        if (!cn.jjxx.modules.sys.utils.CheckStrong.checkPasswordSafe(pwd)) {
                            System.out.println("密码长度为8到16位,必须包含字母和数字，字母区分大小写");
                            model.addAttribute("error", "密码长度为8到16位,必须包含字母和数字，字母区分大小写");
                            return "modules/sys/index/pwdchang";
                        } else {
                            UserUtils.getUser().setChangePwdTimes(5);
                        }
                    } else {
                        UserUtils.getUser().setChangePwdTimes(5);
                    }
                }
            }
        } catch (Exception e) {

        }
        //return "modules/sys/index/index-" + theme;
        return linkUrl;
    }

    /**
     * 获取菜单json数据
     *
     * @author bgg
     * @date 2018-2-23
     */
    @RequestMapping(value = "menuJson", method = RequestMethod.POST)
    public void menuJson(Model model, HttpServletRequest request, HttpServletResponse response) {
        List<Menu> menus = UserUtils.getMenuList();
        StringUtils.printJson(response, menus);
    }

    /**
     * 加载风格
     *
     * @param request
     * @return
     * @title: getTheme
     * @description: TODO(这里用一句话描述这个方法的作用)
     * @return: String
     */
    private String getTheme(HttpServletRequest request) {
        // 默认风格
        String theme = JeewebPropertiesUtil.getConfig("admin.default.theme");
        if (StringUtils.isEmpty(theme)) {
            theme = "ace";
        }
        // cookies配置中的模版
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie == null || StringUtils.isEmpty(cookie.getName())) {
                continue;
            }
            if (cookie.getName().equalsIgnoreCase("theme")) {
                theme = cookie.getValue();
            }
        }
        return theme;
    }

    /**
     * Coookie设置
     */
    @RequestMapping(value = "/theme/{theme}")
    public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request,
                                   HttpServletResponse response) {
        if (StringUtils.isNotBlank(theme)) {
            CookieUtils.setCookie(response, "theme", theme);
        } else {
            theme = CookieUtils.getCookie(request, "theme");
        }
        return "redirect:" + request.getParameter("url");
    }

    @RequestMapping("/pwdchang")
    public String pwdchang() {
        return "modules/sys/index/pwdchang";
    }

    @RequestMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    @RequestMapping("/main")
    public String main() {
        String linkUrl = "modules/sys/index/main";
        boolean bo = false;
        //查询是否关联首页
        EntityWrapper<SysHomePageManageUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("user_id", UserUtils.getUser().getId());
        List<SysHomePageManageUser> list = iSysHomePageManageUserService.selectList(entityWrapper);
        if (list.size() > 0) {
            EntityWrapper<SysHomepageManage> homepageManageEntityWrapper = new EntityWrapper<>();
            homepageManageEntityWrapper.eq("id", list.get(0).getHomePageId());
            List<SysHomepageManage> sysHomepageManages = iSysHomepageManageService.selectList(homepageManageEntityWrapper);
            if (sysHomepageManages.size() > 0) {
                linkUrl = sysHomepageManages.get(0).getHomePageLink();
            } else {
                bo = true;
            }
        } else {
            bo = true;
        }
        if (bo) {
            EntityWrapper<SysHomepageManage> homepageManageEntityWrapper = new EntityWrapper<>();
            homepageManageEntityWrapper.eq("is_default", "1");
            List<SysHomepageManage> sysHomepageManages = iSysHomepageManageService.selectList(homepageManageEntityWrapper);
            if (sysHomepageManages.size() > 0) {
                linkUrl = sysHomepageManages.get(0).getHomePageLink();
            }
        }
        return linkUrl;
        //return "modules/sys/index/main";
    }

    @RequestMapping("/lock")
    public String lock() {
        return "lock";
    }

}
